<?php

namespace app\common\command;

use app\backstage\model\CommissionRecord;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

use app\backstage\model\CommissionChange;
use app\backstage\model\Order;
use app\backstage\model\Wallet;
use think\Exception;
use think\facade\Cache;

class OrderSendCommission extends Command
{
    /**
     * 定义
     */
    protected function configure(){
        $this->setName('OrderSendCommission')->setDescription("计划任务  => Order Send Commission");
    }

    /**
     * 执行
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     * @throws \Exception
     */
    public function execute(Input $input, Output $output)
    {
        $output->writeln('Date Crontab job start => Order Send Commission');
        /*** 这里写计划任务列表集 START ***/

        $this->doSendCommission($output);

        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end => Order Send Commission');
    }

    /**
     * 订单完成
     * @param Output $output
     * @throws \Exception
     */
    public function doSendCommission(Output $output)
    {
        $orderModel = app(Order::class);
        // 查询订单
        $orderList = $orderModel->alias('o')
            ->join(['zr_commission_record' => 'c'], 'c.order_id  = o.id')
            ->where('o.status', 8)
            ->where('c.status', 1)
            ->field('o.id,o.status as o_status,o.order_sn,c.order_id,c.status as c_status')
            ->select();
        foreach ($orderList as  $order) {
            $result = $this->handleSendBalance($order);
            if (!$result['status']) {
                /*** 记录错误 ***/
                $output->writeln('订单号为 '.$order->order_sn.' 的订单发放佣金失败！');
                $output->writeln('错误信息为： '.$result['msg']);
            }
        }
    }

    /**
     * 发放佣金
     * @param $order
     * @return array|bool
     * @throws \Exception
     */
    public function handleSendBalance($order)
    {
        if (!in_array($order->o_status, [8])) {
            return ['status' => false, 'msg' => '订单状态已更改！'];
        }
        \Db::startTrans();
        try {
            // 获取被冻结的佣金
            $commissionRecord = new CommissionRecord();
            $records = $commissionRecord->where(['status' => 1, 'order_id' => $order->id])->select();
            if (count($records) > 0) {
                // 循环
                $commissionChange = new CommissionChange();
                $changes = [];
                foreach ($records as $record) {
                    $wallet = $record->recipientUserWallet;
                    $changes[]     = [
                        'uid'               => $record->recipient_uid,
                        'order_id'          => $order->id,
                        'commission'        => $record->commission,
                        'new_commission'    => $wallet->allow_commission + $record->commission,
                        'type'              => '1',
                        'record_id'         => $record->id
                    ];
                    $wallet->frost_commission -= $record->commission;
                    $wallet->allow_commission += $record->commission;
                    $wallet->save();
                    if ($wallet->frost_commission < 0) {
                        \Db::rollback();
                        return false;
                    }
                }
                $commissionChange->saveAll($changes, false);
                $commissionRecord->save(['status' => 2], ['order_id' => $order->id]);
            }
            // 修改订单状态
            \Db::commit();
            return ['status' => true, 'msg' => '修改成功'];
        } catch (Exception $exception) {
            \Db::rollback();
            return ['status' => false, 'msg' => $exception->getMessage()];
        }
    }

}